import 'package:flutter/material.dart';

/// 配合[CustomScrollView]，使[builder]构建的Widget固定在顶部
class KqSliverPersistentHeader extends SliverPersistentHeader {
  KqSliverPersistentHeader(
      {super.key,
      double minExtent = 0.0,
      required double maxExtent,
      required ChildBuilder builder,
      ShouldRebuild? shouldRebuild,
      super.pinned = true,
      super.floating = false})
      : super(
            delegate: _KqSliverPersistentHeaderDelegate(
          minExtent,
          maxExtent,
          builder,
          shouldRebuild ??
              (oldDelegate) {
                return oldDelegate.maxExtent != maxExtent ||
                    oldDelegate.minExtent != minExtent;
              },
        ));
}

class _KqSliverPersistentHeaderDelegate extends SliverPersistentHeaderDelegate {
  final double _minExtent;
  final double _maxExtent;
  final ChildBuilder _builder;
  final ShouldRebuild _shouldRebuild;

  const _KqSliverPersistentHeaderDelegate(
      this._minExtent, this._maxExtent, this._builder, this._shouldRebuild);

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return _builder(context, shrinkOffset, overlapsContent);
  }

  @override
  double get maxExtent => _maxExtent;

  @override
  double get minExtent => _minExtent;

  @override
  bool shouldRebuild(covariant SliverPersistentHeaderDelegate oldDelegate) {
    return _shouldRebuild(oldDelegate);
  }
}

typedef ChildBuilder = Widget Function(
    BuildContext context, double shrinkOffset, bool overlapsContent);

typedef ShouldRebuild = bool Function(
    SliverPersistentHeaderDelegate oldDelegate);
